import { Controller } from 'egg';

export default class CoursesController extends Controller{
  async list() {
    const page = this.ctx.request.queries.page || 1;
    const data = await this.app.mysql.select('course', {
      where: { del_flag: 0 },
      orders: [['id','desc']], 
      limit: 20,
      offset: (+page - 1) * 20
    });
    const total = await this.app.mysql.count('course', { del_flag: 0 });
    this.ctx.body = { data, total: Math.ceil(total / 20) };
  }

  async create() {
    const data: any = {};
    const body = this.ctx.request.body;
    if (body.id) data.id = body.id;
    if (body.avatar) data.avatar = body.avatar;
    if (body.title) data.title = body.title;
    if (body.description) data.description = body.description;
    try {
      if (!body.id)
        await this.app.mysql.insert('course', data);
      else
        await this.app.mysql.update('course', data);
      this.ctx.body = { status: 0 }
    } catch (e) {
      this.ctx.body = { status: -1, message: e }
    }
  }

  async delete() {
    const { id } = this.ctx.params;
    try {
      await this.app.mysql.update('course', { id, del_flag: 1 });
      this.ctx.body = { status: 0 };
    } catch (e) {
      this.ctx.body = { status: -1, message: e };
    }
  }

}
